<template>
  <div class="register-form-container">
    <a-form
      id="formLogin"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit"
    >
      <a-form-item style="margin-bottom:0;">
        <a-form-item
          label="First Name"
          :colon="false"
          :style="{ display: 'inline-block', width: 'calc(50% - 20px)', 'margin-right': '40px' }"
        >
          <a-input
            v-decorator.trim="[
              'firstName',
              {rules: [{ required: true, message: 'First Name is not valid, please enter' }], validateTrigger: 'change'}
            ]"

            size="large"
            type="text"
            placeholder="First Name"
          />
        </a-form-item>

        <a-form-item
          label="Last Name"
          :colon="false"
          :style="{ display: 'inline-block', width: 'calc(50% - 20px)' }"
        >
          <a-input
            v-decorator.trim="[
              'Last Name',
              {rules: [{ required: true, message: 'Last Name is not valid, please enter' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
            ]"
            size="large"
            type="text"
            placeholder="lastName"
          />
        </a-form-item>
      </a-form-item>

      <a-form-item
        label="Email"
        :colon="false"
      >
        <a-input
          v-decorator.trim="[
            'email',
            {rules: [{ required: true, message: 'Email is not valid, please enter' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
          ]"
          size="large"
          type="text"
          placeholder="Email"
        />
      </a-form-item>

      <a-form-item
        label="Choose a Password"
        :colon="false"
      >
        <a-input-password
          v-decorator.trim="[
            'Choose a Password',
            {rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
          ]"
          size="large"
          type="text"
          placeholder="Choose a Password"
        />
      </a-form-item>

      <a-form-item
        label="Confirm Password"
        :colon="false"
      >
        <a-input-password
          v-decorator.trim="[
            'Confirm Password',
            {rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
          ]"
          size="large"
          type="text"
          placeholder="Confirm Password"
        />
      </a-form-item>

      <a-form-item v-bind="tailFormItemLayout">
        <a-checkbox v-decorator.trim="['agreement', { valuePropName: 'checked' }]">
          I have read and accepted the
          <a
            href=""
            @click.prevent
          >
            XXXagreement
          </a>
        </a-checkbox>
      </a-form-item>

      <a-button
        type="primary"
        size="large"
        block
        :loading="state.loginBtn"
        @click="handleSubmit"
      >
        Register
      </a-button>
    </a-form>

    <div class="login-tips-text">
      Existing account ?
      <router-link
        class="link"
        :to="{ name: 'login' }"
      >
        Login
      </router-link>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import { getSmsCaptcha } from '@/api/auth/login';

export default {
   data() {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    };
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const { state } = this;
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      if (regex.test(value)) {
        state.loginType = 0;
      } else {
        state.loginType = 1;
      }
      callback();
    },
    handleTabClick(key) {
      this.customActiveKey = key;
      // this.form.resetFields()
    },
    handleSubmit(e) {
      e.preventDefault();
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this;

      state.loginBtn = true;

      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha'];

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          console.log('login form', values);
          const loginParams = {
            mobile_or_username: '18291185175',
            password: 'qwertyuiop',
            remember_me: true
          };
          // delete loginParams.username
          // loginParams[!state.loginType ? 'email' : 'username'] = values.username
          // loginParams.password = values.password // md5(values.password)
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch((err) => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false;
            });
        } else {
          setTimeout(() => {
            state.loginBtn = false;
          }, 600);
        }
      });
    },
    getCaptcha(e) {
      e.preventDefault();
      const { form: { validateFields }, state } = this;

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true;

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60;
              state.smsSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);

          const hide = this.$message.loading('验证码发送中..', 0);
          getSmsCaptcha({ mobile: values.mobile }).then((res) => {
            setTimeout(hide, 2500);
            this.$notification.success({
              message: '提示',
              description: `验证码获取成功，您的验证码为：${ res.result.captcha}`,
              duration: 8
            });
          }).catch((err) => {
            setTimeout(hide, 1);
            clearInterval(interval);
            state.time = 60;
            state.smsSendBtn = false;
            this.requestFailed(err);
          });
        }
      });
    },
    stepCaptchaSuccess() {
      this.loginSuccess();
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false;
        this.stepCaptchaVisible = false;
      });
    },
    loginSuccess(res) {
      console.log(res);
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
      this.$router.push({ name: 'analysis' }, () => {
        console.log('onComplete')
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      })
      */
      this.$router.push({ path: '/' });
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: '欢迎回来'
        });
      }, 1000);
      this.isLoginError = false;
    },
    requestFailed(err) {
      this.isLoginError = true;
      this.$notification.error({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      });
    }
  }
};
</script>

<style lang="scss">
.register-form-container {
  input:focus {
    // border: none;
    box-shadow: none;
    border-bottom-color: $theme-color;
  }
  input {
    border: none;
    border-radius: 0;
    border-bottom: 1px solid $gray-16;
  }
  .ant-form label {
    color: $gray-17;
  }
  .ant-form-item {
    margin-bottom: 18px;
  }
  .login-tips-text {
    color: $gray-17;
    margin-top: $margin-xs;
    .link {
      cursor: pointer;
      color: $theme-color;
    }
  }
}
</style>
